package cn.minhx.domain.strategy.service.rule.chain.impl;

import cn.minhx.domain.strategy.repository.IStrategyRepository;
import cn.minhx.domain.strategy.service.rule.chain.AbstractLogicChain;
import cn.minhx.domain.strategy.service.rule.chain.factory.DefaultChainFactory;
import cn.minhx.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 【抽奖责任链】黑名单规则
 *
 * @author min
 */
@Slf4j
@Component("rule_blacklist")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class RuleBlackListLogicChain extends AbstractLogicChain {

    @Resource
    private IStrategyRepository repository;

    @Override
    public DefaultChainFactory.StrategyAwardVO logic(String userId, Long strategyId) {
        log.info("抽奖责任链-黑名单 开始 userId:{} strategyId:{} ruleModel:{}", userId, strategyId, ruleModel());

        // 类似 -> "100:user001,user002,user003"
        String ruleValue = repository.queryStrategyRuleValue(strategyId, ruleModel());

        String[] splitRuleValue = ruleValue.split(Constants.COLON);
        // 黑名单规则配置的奖品ID
        Long awardId = Long.valueOf(splitRuleValue[0]);

        // 此黑名单规则配置的用户
        String[] userBlackIds = splitRuleValue[1].split(Constants.COMMA);
        for (String userBlackId : userBlackIds) {
            // 如果是此黑名单规则匹配的用户，直接返回此奖品
            if (userId.equals(userBlackId)) {
                log.info("抽奖责任链-黑名单 接管 userId:{} strategyId:{} ruleModel:{} awardId:{}",
                        userId, strategyId, ruleModel(), awardId);
                return DefaultChainFactory.StrategyAwardVO.builder().awardId(awardId).logicModel(ruleModel()).build();
            }
        }

        // 未命中，继续执行下一个节点
        log.info("抽奖责任链-黑名单 放行 userId:{} strategyId:{} ruleModel:{}", userId, strategyId, ruleModel());
        return next().logic(userId, strategyId);
    }

    @Override
    protected String ruleModel() {
        return DefaultChainFactory.LogicModel.RULE_BLACKLIST.getCode();
    }

}
